public class CalculateStageWinRate {
    
    public List<Contact> contactList {get;set;}
    public Opportunity opp {get;set;}
    public List<ContactWarpper> cWList{get;set;}

    public Account oppAcc {get;set;}
    public Department__c oppAccDept {get;set;}

    List<WinRatioTeam__c> wrtList = new List<WinRatioTeam__c>();
    List<StageWinRate__c> slist{get;set;}
    public Boolean isSuccess {get;set;}
    public String  msg {get;set;}//
    public CalculateStageWinRate(ApexPages.StandardController con) 
    {

        opp = (Opportunity)con.getRecord();
        System.debug('*** Opportunity: ' + opp);

        Set<Id> cidSet = new Set<Id>();
        //List<Opportunity> opList=[select Id, Name, StageName, (select Id, ContactId, IsDeleted from OpportunityContactRoles) from Opportunity where Id =: opp.Id];
        List<Opportunity> opList = [select Id, Name, StageName, StageOrder__c, AccountId ,
        LostReason__c, ContractTime__c,LostReasoneDesc__c,Successfulcompany__c,RecordTypeName__c,
        Winningcompanychannel__c,SuccessfulBrand__c,SuccessfulModel__c,WhetherParticipate__c,
        ExecuteCompany__c,ExecutiveCompany__c,PurchaseRoot__c
        from Opportunity where id =: opp.Id];

        
        
        if(!opList.isEmpty())
        {
            opp=opList.get(0);

             oppAcc = [select Id,Name, Phone,Address__c,RegisterAmount__c,Province__c,
            District__c,Postcode__c,Company__c,LastYearRevenue__c,Actual_Controller__c,Master_Shareholder__c,
            Category__c,CustomerAttribute__c,Level__c,Artificial__c,City__c,
            BedNumOpen__c,SpecialDepart__c from Account where Id=:opp.AccountId];


            System.debug('*** Opportunity: ' + opp);

            contactList = [select Id, Name, Post__c, Departments__c from Contact where AccountId =: opp.AccountId ];
            System.debug('*** contactList: '+ contactList);
            //上阶段的联系人及赢单率
            //String UpRecordType = '';            
            slist = [select Name from StageWinRate__c where Opportunity__c =: opp.Id  and CountChild__c > 0 order by CreatedDate desc limit 1]; 
            if(slist.isEmpty()){
                System.debug('*** @slist: 为空');
                slist = [select Name from StageWinRate__c where Opportunity__c =: opp.Id order by CreatedDate desc limit 1]; 
                System.debug('*** @slist: '+slist);
            }
            System.debug('*** @slist: '+slist);
            
        }

    }
    public void getContactsAndRito(){
            isSuccess = false;
            if(!slist.isEmpty())
            {
                wrtList=[select StageWinRate__c,Contact__c,Weight__c,SupportRatio__c from WinRatioTeam__c where Opportunity__c =: opp.Id and StageWinRate__c =: slist[0].Id];
            }
            // Map<Contact.Id,WinRatioTeam__c> wrtMap = new Map<Contact.Id,WinRatioTeam__c>([select Contact__c,Weight__c,SupportRatio__c,StageWinRate__c from WinRatioTeam__c where Opportunity__c =: opp.Id and StageWinRate__c =: UpRecordType]);
            System.debug('*** @wrtList:'+wrtList);
            Map<Id,WinRatioTeam__c> wrtMap = new Map<Id,WinRatioTeam__c>();
            if(!wrtList.isEmpty())
            {
                for(WinRatioTeam__c w :wrtList)
                {
                    wrtMap.put(w.Contact__c,w);
                }

            }

            System.debug('*** wrtMap: '+wrtMap);

            cWList = new List<ContactWarpper>();
            for(Contact c: contactList)
            {
                ContactWarpper cw = new ContactWarpper();
                //cw.isChoosed = false;
                cw.cont = c;
                WinRatioTeam__c w = new WinRatioTeam__c();
                if(wrtMap.containsKey(c.Id))
                {
                    WinRatioTeam__c wr = wrtMap.get(c.Id);
                    w.SupportRatio__c = wr.SupportRatio__c;
                    w.Weight__c = wr.Weight__c;
                    // w.StageWinRate__c =wr.StageWinRate__c;
                    cw.wrt = w; 
                    cw.isChoosed = true;
                }
                else
                {
                    cw.wrt = w;
                    cw.isChoosed = false;
                }

                cWList.add(cw);
            }
            System.debug('*** cWList: '+ cWList);
    }
    public void NewStageWinRate()
    {
        msg = '';
        isSuccess = false;
        if(cWList != null)
        {
            //获取当前阶段
            List<StageWinRate__c> swrlist = [select Id, Name from StageWinRate__c where Opportunity__c =: opp.Id order by CreatedDate desc limit 1];
             if(swrlist.size() > 0){
                 StageWinRate__c swr = swrlist[0];
                 List<WinRatioTeam__c> nwList = new List<WinRatioTeam__c>();
              
                 Double accountW = 0;
                 System.debug('*** cWList:  '+ cWList);
                 for(ContactWarpper cw : cWList)
                 {
                     if(cw.isChoosed)
                     {

                         if(cw.wrt.SupportRatio__c == null || cw.wrt.Weight__c == null){
                            msg = '【支持率】【权重】 不能为空!';
                           // ApexPages.addMessage(new ApexPages.Message(ApexPages.Severity.ERROR,'【支持率】【权重】 不能为空!'));
                             return ; 
                         }
                         if(cw.wrt.SupportRatio__c >100)
                         {
                            msg = '【支持率】不能超过100%！';
                            // ApexPages.addMessage(new ApexPages.Message(ApexPages.Severity.ERROR,'【支持率】不能超过100%！'));
                             return ;
                         }

                         if(cw.wrt.Weight__c != null){
                             accountW = accountW + cw.wrt.Weight__c;
                         }
                         WinRatioTeam__c wrt = cw.wrt;
                         wrt.Opportunity__c = opp.Id;
                         wrt.Name = cw.cont.Name;
                         wrt.contact__c = cw.cont.Id;
                         wrt.StageWinRate__c = swr.Id;
                         nwList.add(wrt);
                     }
                 }
                 System.debug('*** accountW: '+accountW);
                 if(accountW >100)
                 {
                     //ApexPages.addMessage(new ApexPages.Message(ApexPages.Severity.ERROR,Label.Err_WeightRule));//'【权重】和不能超过100%！'
                     msg = Label.Err_WeightRule;
                     return ;
                 }
                 if(!wrtList.isEmpty()){
                     if(wrtList[0].StageWinRate__c == swr.Id){  //删除当前阶段
                         delete wrtList;
                     }
                 }
                 if(!nwList.isEmpty())
                 {
                     try
                     {
                         System.debug('*** @nwList: ' + nwList);
                         insert nwList;
                         System.debug('*** @nwList: ' + wrtList);
                         system.debug(nwList+'===================================');
                         isSuccess = true;
                         msg = '保存成功!';
                     }
                     catch(Exception e)
                     {
                        System.debug(e.getMessage());
                       // ApexPages.addMessage(new ApexPages.Message(ApexPages.Severity.WARNING,Label.Err_SupportRadioRule));//'【支持率】不能超过100%！'
                         msg = Label.Err_SupportRadioRule;
                     }
                     //ApexPages.addMessage(new ApexPages.Message(ApexPages.Severity.INFO,'已创建相应【阶段赢单阶段赢单率】以及【赢单率小组】的记录！点击"<a href=\'/' + opp.Id + '\' style="color:blue">这里</a>"返回'));
                     //return new ApexPages.StandardController(opp).view();
                 }
                 else
                 {
                     //ApexPages.addMessage(new ApexPages.Message(ApexPages.Severity.WARNING,Label.Err_OpportunityNoChooseContact));//'未选择任何联系人！'
                     System.debug('不处理！');
                     msg = Label.Err_OpportunityNoChooseContact;
                    return ;
                 }
             }
         }
        // return null;
    }

    public void dropBill(){
        isSuccess = false;
        msg = '';
        try{
            opp.StageName = '失败';
            update opp;
            msg = '保存成功!';
            isSuccess = true;
        }catch(Exception e ){
            isSuccess  = false;
            msg = '保存失败 :'+e.getMessage();
        }
    }
    public void upgradeStage1(){
        upgradeStage();
    }
    public Boolean upgradeStage (){
         isSuccess = false;
        msg = '';
        if(opp.StageName == '意向'){
            opp.StageName = '立项';
        }else if(opp.StageName == '立项'){
            opp.StageName = '方案谈判';

        }else if(opp.StageName == '方案谈判'){
            opp.StageName = '招标';
        }else if(opp.StageName == '招标'){
            Integer qcount = [select count() from Quote where OpportunityId =:opp.Id];
            Integer mcount = [select count() from Measure_Calculate__c where Opportunity__c =:opp.Id];

            opp.StageName = '合同签订';
            if(qcount > 0 || mcount > 0){
                msg = '有报价或测算的业务机会不能手动升迁到合同签订!';
                isSuccess = false;
                return false;
            }
        }

       
        try{
            update opp;
            msg = '保存成功!';
            isSuccess = true;
            return true;
        }catch(Exception e ){
             msg = '保存失败 :'+e.getMessage();
            isSuccess = false;
            return false;
        }
    }
     public void updateAcc(){
        isSuccess = false;
        msg = '';
        try{
            update oppAcc;
            isSuccess =  upgradeStage();
        }catch(Exception e ){
            isSuccess  = false;
            msg = '保存失败 :'+e.getMessage();
        }
    }
    public Class ContactWarpper
    {
        public Boolean isChoosed {get;set;}
        public Contact cont {get;set;}
        public WinRatioTeam__c wrt {get;set;}

    }
}